package com.sen.common.orm;

import java.util.HashMap;
import java.util.Map;

/**
 * 分页上下文
 * @author sen
 */
public final class PageContext {

	private static final String TOTAL_ELEMENTS = "totalElements";
	private static final String PAGE_SIZE = "pageSize";
	private static ThreadLocal<Map<String, Integer>> pageLocal = new ThreadLocal<Map<String, Integer>>();

	private PageContext() {
		// empty!
	}
	
	public static Integer getPageSize() {
		if ((pageLocal == null) || (pageLocal.get() == null)) {
			return Integer.valueOf(0);
		}
		Integer pageSize = pageLocal.get().get(PAGE_SIZE);
		if (pageSize == null) {
			return Integer.valueOf(0);
		}
		return pageSize;
	}

	public static Integer getTotalElements() {
		if ((pageLocal == null) || (pageLocal.get() == null)) {
			return Integer.valueOf(0);
		}
		Integer totalElements = pageLocal.get().get(TOTAL_ELEMENTS);
		if (totalElements == null) {
			return Integer.valueOf(0);
		}
		return totalElements;
	}
	
	public static boolean isCountTotalPermitted() {
		return getTotalElements().intValue() == 0;
	}

	public static void setPageSize(Integer pageSize) {
		Map<String, Integer> map = pageLocal.get();
		if (map == null) {
			map = new HashMap<String, Integer>();
			pageLocal.set(map);
		}
		map.put(PAGE_SIZE, pageSize);
	}

	public static void setTotalElements(Integer totalElements) {
		Map<String, Integer> map = pageLocal.get();
		if (map == null) {
			map = new HashMap<String, Integer>();
			pageLocal.set(map);
		}
		map.put(TOTAL_ELEMENTS, totalElements);
	}

	/**
	 * 不进行sql求总的操作.
	 */
	public static void forbidCountTotal() {
		setTotalElements(-1);
	}
	
	public static void clean() {
		pageLocal.remove();
	}
}
